package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;

import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Override
    public Result order(Map map) throws Exception{
        //先检查用户所选择的日期是否已经进行了预约设置，如果没有，则无法进行预约
        //获取用户预约日期
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findCountByOrderDate(DateUtils.parseString2Date(orderDate));
        if(orderSetting == null){
            //指定日期没有完成预约设置，返回失败result
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //若指定日期已经完成预约设置，则查看预约人数是否已经约满，如果已经约满也返回失败result
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //已经约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //检查是否是重复预约（一人一天同一个套餐只能预约一次），如果是重复预约则无法完成再次预约
        //获取用户页面输入的手机号
        String telephone = (String) map.get("telephone");
        //获取会员信息
        Member member = memberDao.findByTelephone(telephone);
        if(member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
           // String orderType = (String) map.get("orderType");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        if(member == null) {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }

        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
       //更新以预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //设置订单表和地址表之间的关联
        orderDao.setOrderAndAddress(order.getId(),(Integer)map.get("addressIds"));

        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    @Override
    //根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
    public Map findById(Integer id) throws Exception{
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    /**
     * 分页查询所有数据进行回显
     *
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);

        Map<String, Object> conditions = (Map<String, Object>) JSON.parse(queryString);
        List<Map> list = orderDao.findListByCondition(conditions);
        PageInfo<Map> pageInfo = new PageInfo<>(list);

        long total = pageInfo.getTotal();
        List<Map> list1 = pageInfo.getList();

        return new PageResult(total, list1);
    }

    /**
     * 添加预约信息
     *
     * @param map
     * @param setmealId
     */
    public Result add(Map map, Integer setmealId) throws Exception {
        String phoneNumber = (String) map.get("phoneNumber");
        String orderDate = (String) map.get("orderDate");
        String name = (String) map.get("name");
        String orderType = (String) map.get("orderType");
        String idCard = (String) map.get("idCard");

        String birthday = (String) map.get("birthday");
        String sex = (String) map.get("sex");
        //1.检查用户选择的预约日期是否设置了可预约，如果没有设置则无法进行预约
        OrderSetting orderSetting = orderSettingDao.findCountByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //选择的日期没有设置可预约，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查用户选择的日期可预约人数是否为0，或已预约满，如未设置或已约满，则不能进行预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            //用户选择的预约日期可预约人数为0或已预约满，无法完成预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //3.检查用户是否是会员，如果是会员直接预约，如果不是会员，先自动注册会员，然后进行预约

        Member member = memberDao.findByTelephone(phoneNumber);
        if (member == null) {
            //用户不是会员，自动注册会员
            member = new Member();
            member.setName(name);
            member.setPhoneNumber(phoneNumber);
            member.setIdCard(idCard);
            member.setSex(sex);
            member.setBirthday(DateUtils.parseString2Date(birthday));
            member.setRegTime(new Date());
            memberDao.add(member);
        } else {
            //4.检查会员用户是否重复预约，如果重复预约，则不能进行预约（根据日期，预约套餐，预约用户进行判断）
            //用户是会员，检查是否重复预约
            Integer memberId = member.getId();
            Date date = DateUtils.parseString2Date(orderDate);
            Order order = new Order(memberId, date, setmealId);
            List<Order> orders = orderDao.findByCondition(order);
            if (orders != null && orders.size() > 0) {
                //已经预约过了，不可重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //5.预约完成，更新已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType(orderType);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(setmealId);
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    /**
     * 根据ID删除数据
     *
     * @param id
     */
    public void deleteById(Integer id) {
        orderDao.deleteByOrderId(id);
        orderDao.deleteById(id);
    }

    /**
     * 根据ID查询回显
     *
     * @param id
     * @return
     */
    public Map findByOrderId(Integer id) {
        Map<String, Object> map = orderDao.findByOrderId(id);
        return map;
    }

    /**
     * 一键修改预约状态
     *
     * @param map
     */
    public void changeStatus(Map<String, Object> map) {
        orderDao.changeStatus(map);
    }

    /**
     * 根据ID查询套餐信息，用于回显
     *
     * @param id
     * @return
     */
    public Setmeal findSetmealById(Integer id) {
        Setmeal setmeal = orderDao.findSetmealById(id);
        return setmeal;
    }

    /**
     * 修改预约信息
     *
     * @param map
     * @param setmealId
     */
    public void update(Map map, Integer setmealId) throws Exception {
        Integer oid = (Integer) map.get("oid");
        String phoneNumber = (String) map.get("phoneNumber");
        String orderDate = (String) map.get("orderDate");
        String name = (String) map.get("name");
        String orderType = (String) map.get("orderType");
        String idCard = (String) map.get("idCard");
        String birthday = (String) map.get("birthday");
        String sex = (String) map.get("sex");

        Order order = orderDao.findById(oid);

        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType(orderType);
        order.setSetmealId(setmealId);
        System.out.println(order);
        orderDao.edit(order);

        System.out.println(order);

        Integer member_id = order.getMemberId();

        Member member = new Member();
        member.setId(member_id);
        member.setName(name);
        member.setPhoneNumber(phoneNumber);
        member.setIdCard(idCard);
        member.setSex(sex);
        member.setBirthday(DateUtils.parseString2Date(birthday));
        memberDao.edit(member);
    }

    @Override
    public List<Integer> findtoOrderStatus(ArrayList<String> dayList) {
        List<Integer> map = new ArrayList<>();

        /*预约数*/
        for (String s : dayList) {
            Integer visitsCountByDate = orderDao.findOrderCountoneDate(s);

            map.add(visitsCountByDate);
        }

        return map;
    }

    @Override
    public List<Integer> findtoOrderList(ArrayList<String> dayList) {
        List<Integer> map1 = new ArrayList<>();
        for (String s1 : dayList) {
            /*orderDao.findVisitsCountAfterDate*/
            Integer visitsCountAfterDate1 = orderDao.findVisitsCountoneDate(s1);
            map1.add(visitsCountAfterDate1);
        }
        return map1;
    }

    @Override
    public void statusEdit(Order order) {
        orderDao.statusEdit(order);
    }

    @Override
    public List<Map<String, Object>> findHistoryRecord(String telephone, String startDate, String endDate) {
        return orderDao.findHistoryRecord(telephone,startDate,endDate);
    }

    @Override
    public Map<String, Object> getRecordDetails(Integer id) {
        Map<String, Object> map = orderDao.getRecordDetails(id);
        List<Map<String, Object>> adressList = orderDao.getAddress(id);
        if (adressList != null && adressList.size() > 0) {
            map.put("a_address", adressList.get(0).get("a_address"));
        } else {
            map.put("a_address", "暂无信息");
        }
        return map;
    }
}

